package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.file.service.impl.OSSAliyunFileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @author stone
 * @description 针对表【wm_material(自媒体图文素材信息表)】的数据库操作Service实现
 * @createDate 2023-03-21 16:38:58
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial>
        implements WmMaterialService {

    @Value("${file.oss.prefix}")
    private String prefix;

    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private OSSAliyunFileStorageService storageService;

    @Autowired
    private WmNewsMaterialServiceImpl newsMaterialService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        // 登录参数校验
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (Objects.isNull(wmUser)) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        if (Objects.isNull(multipartFile) || multipartFile.getSize() == 0) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE, "上传文件不能为空");
        }
        // 上传oss
        String originalFilename = multipartFile.getOriginalFilename();
        // 校验文件格式
        if (!checkFileSuffix(originalFilename)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }
        String filePath = null;
        try {
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            filePath = storageService.store(prefix, uuid + suffix, multipartFile.getInputStream());
            log.info("{}文件上传路径：{}", originalFilename, filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 保存 封装全路径返回
        WmMaterial material = new WmMaterial();
        material.setUserId(wmUser.getId());
        material.setUrl(filePath);
        material.setType(Integer.valueOf(WemediaConstants.PICTURE_TYPE));
        material.setIsCollection(Integer.valueOf(WemediaConstants.CANCEL_COLLECT_MATERIAL));
        material.setCreatedTime(new Date());
        this.save(material);
        material.setUrl(webSite + material.getUrl());
        log.info("上传文件的全路径：{}", material.getUrl());
        return ResponseResult.okResult(material);
    }

    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        WmUser wmUser = WmThreadLocalUtils.getUser();
        if (Objects.isNull(wmUser)) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (Objects.isNull(dto.getIsCollection())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        dto.checkParam();

        // 分页
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(WmMaterial::getIsCollection, dto.getIsCollection())
                .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
                .orderByAsc(WmMaterial::getCreatedTime);

        IPage<WmMaterial> resultPage = this.page(page, wrapper);
        List<WmMaterial> records = resultPage.getRecords();
        if (CollectionUtils.isNotEmpty(records)) {
            for (WmMaterial record : records) {
                // 全封装素材 外网访问全路径
                record.setUrl(webSite + record.getUrl());
            }
        }
        return new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal(), records);
    }


    @Override
    public ResponseResult delPicture(Integer id) {

        if (Objects.isNull(id)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmMaterial material = this.getById(id);
        if (Objects.isNull(material)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        // 查询 文章与素材关联表 存在不允许删除
        int count = newsMaterialService.count(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        // 删除素材以及oss
        this.removeById(id);
        storageService.delete(material.getUrl());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short cancelCollectMaterial) {
        if (Objects.isNull(id)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        if (Objects.isNull(cancelCollectMaterial)) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmMaterial material = this.getById(id);
        if (Objects.isNull(material)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer userId = WmThreadLocalUtils.getUser().getId();
        if (!userId.equals(material.getUserId())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "只允许收藏自己上传的素材");
        }
        // 只允许修改当前登录人 更新取消收藏状态
        this.update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection, cancelCollectMaterial)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, userId)
        );

        return ResponseResult.okResult();
    }

    /**
     * 校验上传文件的后缀
     *
     * @param path
     * @return
     */
    private boolean checkFileSuffix(String path) {
        List<String> suffixList = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
        for (String str : suffixList) {
            if (path.endsWith(str)) {
                return true;
            }
        }
        return false;
    }
}




